package org.jetnuke.util;

import java.io.File;
import java.sql.Connection;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;

import net.jforum.ConfigLoader;
import net.jforum.DBConnection;
import net.jforum.ForumStartup;
import net.jforum.JForumExecutionContext;
import net.jforum.exceptions.ForumStartupException;
import net.jforum.repository.ModulesRepository;
import net.jforum.repository.RankingRepository;
import net.jforum.repository.SmiliesRepository;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.jetnuke.common.Configuration;

public class JForumUtil {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(JForumUtil.class);

	public static void initJForum(ServletContext servletContext,
			ServletConfig config,boolean isDatabaseUp) {

		if (logger.isDebugEnabled()) {
			logger.debug("initJForum(ServletConfig) - start"); //$NON-NLS-1$
		}
		boolean debug = false;
		try {
			String appPath = config.getServletContext().getRealPath("");
			debug = "true".equals(config.getInitParameter("development"));

			DOMConfigurator.configure(appPath + "/WEB-INF/log4j.xml");
			ConfigLoader.startSystemglobals(appPath);
			ConfigLoader.startCacheEngine();

			// Configure the template engine
			freemarker.template.Configuration templateCfg = new freemarker.template.Configuration();
			templateCfg.setDirectoryForTemplateLoading(new File(SystemGlobals
					.getApplicationPath()
					+ "/templates"));
			templateCfg.setTemplateUpdateDelay(2);
			templateCfg.setSetting("number_format", "#");
			templateCfg.setSharedVariable("startupTime", new Long(new Date()
					.getTime()));

			ModulesRepository.init(SystemGlobals
					.getValue(ConfigKeys.CONFIG_DIR));
			JetUtil.loadConfigStuff();
			if (!debug) {
				templateCfg.setTemplateUpdateDelay(3600);
			}

			JForumExecutionContext.setTemplateConfig(templateCfg);
		} catch (Exception e) {
			logger.error("initJForum(ServletConfig)", e); //$NON-NLS-1$

			throw new ForumStartupException("Error while starting JForum", e);
		}
		JetUtil.startFrontController();

		// Start database
		try {
			isDatabaseUp = ForumStartup.startDatabase();
		} catch (RuntimeException e1) {
			logger.error("initJForum(ServletConfig)", e1); //$NON-NLS-1$

			e1.printStackTrace();
		}
		if (isDatabaseUp) {
			initDatabaseRelatedStuff(servletContext);
		}
		if (logger.isDebugEnabled()) {
			logger.debug("initJForum(ServletConfig) - end"); //$NON-NLS-1$
		}
	}

	public static void initDatabaseRelatedStuff(ServletContext servletContext) {
		if (logger.isDebugEnabled()) {
			logger.debug("initDatabaseRelatedStuff() - start"); //$NON-NLS-1$
		}

		Connection conn = null;

		try {
			conn = DBConnection.getImplementation().getConnection();
			JForumExecutionContext ex = JForumExecutionContext.get();
			ex.setConnection(conn);
			JForumExecutionContext.set(ex);

			// Init general forum stuff
			ForumStartup.startForumRepository();
			RankingRepository.loadRanks();

			SmiliesRepository.loadSmilies();

		} catch (Exception e) {
			logger.error("initDatabaseRelatedStuff()", e); //$NON-NLS-1$

			throw new ForumStartupException("Error while starting jforum", e);
		}
		Configuration cfg = new Configuration(servletContext);
		servletContext.setAttribute("_cfg", cfg);

		if (logger.isDebugEnabled()) {
			logger.debug("initDatabaseRelatedStuff() - end"); //$NON-NLS-1$
		}
	}
}
